package sunmi.payment.L3;

import android.content.Intent;

import java.util.List;

import mi.payment.admin.SystemUserHomePageActivity;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.Params;
import mi.payment.controller.ParamsInitCtrl;
import mi.payment.controller.SettlementCtrl;
import mi.payment.controller.SignOutCtrl;
import mi.payment.db.PayDetailModel;
import mi.payment.db.UserInfoModel;
import mi.payment.db.dao.PayDetail;
import mi.payment.interfaces.ITaskListener.DefaultTaskListener;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.settings.TransactionOtherOperation;
import mi.payment.transaction.authorize.PreAuthorizeSwingCardActivity;
import mi.payment.transaction.authorize.complete.PreAuthorizeCompleteSwingActivity;
import mi.payment.transaction.authorize.complete.revoke.PreAuthorizeCompleteRevokeActivity;
import mi.payment.transaction.authorize.complete.revoke.PreAuthorizeCompleteRevokeSwingActivity;
import mi.payment.transaction.authorize.revoke.PreAuthorizeRevokeSwingActivity;
import mi.payment.transaction.balance.BalanceSwingCardActivity;
import mi.payment.transaction.refund.ReturnGoodsInputAdminPwd;
import mi.payment.transaction.revoke.RevokeCodeController;
import mi.payment.transaction.revoke.RevokeCodeInputAdminPwdActivity;
import mi.payment.transaction.revoke.RevokeInputAdminPwdActivity;
import mi.payment.transaction.revoke.RevokeMainActivity;
import mi.payment.transaction.revoke.RevokeSwingCardActivity;
import mi.payment.transaction.sale.ConsumeSwingCardActivity;
import mi.payment.transaction.sale.PayOrderResultQueryController;
import mi.payment.transaction.sale.code.CodeActivity;
import mi.payment.transaction.sale.code.ScanActivity;
import mi.payment.ui.print.FillInTheCertificateActivity;
import mi.payment.ui.print.TransactionPrintActivity;
import mi.payment.ui.print.helper.BasePrintController;
import mi.payment.ui.print.helper.PrintController;
import mi.payment.ui.qr.code.ScanConfig;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.print.DataPrinterKernel;
import sunmi.sunmiui.utils.LogUtil;

/**
 * L3 工具类
 *
 * @author Lee64 on 2017/4/26.
 */
public class L3Handler {

    private static final String TAG = "L3Handler";

    private L3Route mL3Route;
    private PayDetailModel mPayDetailModel;

    L3Handler(L3Route context) {
        this.mL3Route = context;
        mPayDetailModel = PayDetailModel.getInstance();
    }

    public static boolean isL3Process() {
        return Params.sL3Params != null;
    }

    /**
     * 处理消费
     */
    public void handleConsume() {
        // 金额校验
        long money = Params.sL3Params.amount;
        if (money <= 0 || money > 999999999) {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_INVALID_AMOUNT);
            return;
        }

        final L3Params params = Params.sL3Params;
        final String amount = MoneyUtils.longCent2DoubleMoneyStr(params.amount);

        // 订单支付接口(通联支持)
        if (params.transType == 21) {
            params.isCustomOrderNo = true;
        }

        switch (params.paymentType) {
            case L3Constant.PayType.BARCODE_TYPE_SELECT:
                openActivity(L3SelectConsumptionActivity.class);
                break;
            case L3Constant.PayType.BARCODE_TYPE_BANK:
                ConsumeSwingCardActivity.startAction(mL3Route, amount);
                break;
            case L3Constant.PayType.BARCODE_TYPE_AliPay_SCAN:
                ScanActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_AliPay);
                break;
            case L3Constant.PayType.BARCODE_TYPE_AliPay_QR:
                CodeActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_AliPay);
                break;
            case L3Constant.PayType.BARCODE_TYPE_WeChat_SCAN:
                ScanActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_WeChat);
                break;
            case L3Constant.PayType.BARCODE_TYPE_WeChat_QR:
                CodeActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_WeChat);
                break;
            case L3Constant.PayType.BARCODE_TYPE_UNION_SCAN:
                ScanActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_UnionPay_Wallet);
                break;
            case L3Constant.PayType.BARCODE_TYPE_UNION_QR:
                CodeActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_UnionPay_Wallet);
                break;
            case L3Constant.PayType.BARCODE_TYPE_ALL_SCAN_QR:
                ScanActivity.startAction(mL3Route, amount, ScanConfig.PLATFORM_ALL);
                break;
            default:
                openActivity(L3SelectConsumptionActivity.class);
                break;
        }
    }

    /**
     * 处理消费撤销
     */
    public void handleConsumeRevocation() {
        boolean finish = true;
        // 保存是否输入主管密码
        boolean isManagePwd = Params.sL3Params.isManagePwd;
        TransactionOtherOperation.getInstance().saveInputDirectorPsd(isManagePwd);

        // 获取流水号
        String oriVoucherNo = Params.sL3Params.oriVoucherNo;
        LogUtil.e(TAG, "是否输入主管密码:" + isManagePwd + " 获取流水号:" + oriVoucherNo);

        if (oriVoucherNo == null || oriVoucherNo.length() == 0) {
            RevokeMainActivity.startAction(mL3Route);
        } else {
            PayDetail payDetail = mPayDetailModel.getPayDetailById(oriVoucherNo);
            if (payDetail == null) {
                RevokeMainActivity.startAction(mL3Route);
            } else {
                int payType = Params.sL3Params.paymentType;
                switch (payType) {
                    case L3Constant.PayType.BARCODE_TYPE_SELECT:
                        RevokeMainActivity.startAction(mL3Route);
                        break;
                    case L3Constant.PayType.BARCODE_TYPE_BANK:
                        bankConsumeRevocationIsPWD(isManagePwd, payDetail);
                        break;
                    case L3Constant.PayType.BARCODE_TYPE_WeChat_QR:
                    case L3Constant.PayType.BARCODE_TYPE_WeChat_SCAN:
                    case L3Constant.PayType.BARCODE_TYPE_AliPay_QR:
                    case L3Constant.PayType.BARCODE_TYPE_AliPay_SCAN:
                    case L3Constant.PayType.BARCODE_TYPE_UNION_QR:
                    case L3Constant.PayType.BARCODE_TYPE_UNION_SCAN:
                        finish = false;
                        qrCodeConsumeRevocationIsPWD(isManagePwd, payDetail);
                        break;
                    default:
                        int platform = payDetail.getTransPlatform();
                        if (platform == 0) {
                            bankConsumeRevocationIsPWD(isManagePwd, payDetail);
                        } else if (platform == 1 || platform == 2) {
                            finish = false;
                            qrCodeConsumeRevocationIsPWD(isManagePwd, payDetail);
                        } else {
                            openActivity(RevokeMainActivity.class);
                        }
                        break;
                }
            }
        }
        if (finish) {
            mL3Route.finish();
        }
    }

    // 银行卡消费撤销
    private void bankConsumeRevocationIsPWD(boolean pwd, PayDetail payDetail) {
        if (pwd) {
            RevokeInputAdminPwdActivity.startAction(mL3Route, payDetail);
        } else {
            RevokeSwingCardActivity.startAction(mL3Route, payDetail);
        }
    }

    // 二维码消费撤销
    private void qrCodeConsumeRevocationIsPWD(boolean pwd, PayDetail payDetail) {
        if (pwd) {
            RevokeCodeInputAdminPwdActivity.startAction(mL3Route, payDetail);
            mL3Route.finish();
        } else {
            RevokeCodeController controller = new RevokeCodeController(mL3Route);
            TradeData tradeData = controller.initTradeData(payDetail);
            controller.qrCodeTransRevoke(tradeData);
        }
    }

    /**
     * 处理退货
     */
    public void handleReturnGoods() {
        final L3Params params = Params.sL3Params;
        TransactionOtherOperation transactionOtherOperation = TransactionOtherOperation.getInstance();
        // 最大退货金额
        long maxAmount = transactionOtherOperation.getTransactionOtherSettings().getMaximumReturnAmount();
        if (params.amount > maxAmount) {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_EXCEED_MAX_AMOUNT);
        } else {
            // 保存是否输入主管密码
            transactionOtherOperation.saveInputDirectorPsd(params.isManagePwd);
            LogUtil.e(TAG, "是否输入主管密码:" + params.isManagePwd);
            openActivity(ReturnGoodsInputAdminPwd.class);
        }
    }

    /**
     * 处理预授权
     */
    public void handlePreAuthorizeConsume() {
        // 金额校验
        long money = Params.sL3Params.amount;
        if (money <= 0 || money > 999999999) {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_INVALID_AMOUNT);
            return;
        }
        String amount = MoneyUtils.longCent2DoubleMoneyStr(Params.sL3Params.amount);
        PreAuthorizeSwingCardActivity.startAction(mL3Route, amount);
    }

    /**
     * 处理预授权撤销
     */
    public void handlePreAuthorizeRevoke() {
        PreAuthorizeRevokeSwingActivity.startAction(mL3Route);
    }

    /**
     * 处理预授权完成
     */
    public void handlePreAuthorizeComplete() {
        openActivity(PreAuthorizeCompleteSwingActivity.class);
    }

    /**
     * 处理预授权完成撤销
     */
    public void handlePreAuthorizeCompleteRevoke() {
        // 保存是否输入主管密码
        TransactionOtherOperation instance = TransactionOtherOperation.getInstance();
        instance.saveInputDirectorPsd(Params.sL3Params.isManagePwd);

        // 获取流水号
        String voucherNo = Params.sL3Params.oriVoucherNo;
        LogUtil.e(TAG, "是否输入主管密码:" + Params.sL3Params.isManagePwd + " 获取流水号:" + voucherNo);
        if (voucherNo != null && voucherNo.length() > 0) {
            PayDetail payDetail = mPayDetailModel.getPayDetailById(voucherNo);
            if (payDetail == null) {
                openActivity(PreAuthorizeCompleteRevokeActivity.class);
            } else {
                PreAuthorizeCompleteRevokeSwingActivity.startAction(mL3Route, payDetail);
            }
        } else {
            openActivity(PreAuthorizeCompleteRevokeActivity.class);
        }
    }

    /**
     * 7.结算
     */
    public void handleSettlement() {
        SettlementCtrl settlementCtrl = new SettlementCtrl(mL3Route);
        settlementCtrl.settlement();
    }

    /**
     * 8.签到
     */
    public void handleSignIn() {
        ParamsInitCtrl ctrl = new ParamsInitCtrl(mL3Route);
        ctrl.paramsInit(new DefaultTaskListener<String>() {

            @Override
            public void onTaskSuccess(String ret) {
                L3BroadcastHelper.sendSuccessBroadcast(mL3Route);
                mL3Route.finish();
            }

            @Override
            public void onTaskFailed(String ret) {
                L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_SIGN_FAIL, ret);
                mL3Route.finish();
            }

        });
    }

    /**
     * 9.余额查询
     */
    public void handleQueryBalance() {
        BalanceSwingCardActivity.startAction(mL3Route);
    }

    /**
     * 10.系统管理
     */
    public void handleSystemManagement() {
        Params.userInfo = UserInfoModel.getInstance().queryUserInfoById("99");
        SystemUserHomePageActivity.startAction(mL3Route);
    }

    /**
     * 11.交易打印
     * 如果传入凭证号，则打印指定的一笔交易
     * 如果指定最后一笔交易，则打印最后一笔交易
     * 如果传入isOnlyPrint为true，则不打印直接返回
     * 打印顺序：凭证号，最后一笔交易
     * 注意：只打印成功的交易
     */
    public void handlePrint() {
        String transId = Params.sL3Params.transId;
        String oriVoucherNo = Params.sL3Params.oriVoucherNo;
        boolean isOnlyPrint = Params.sL3Params.isOnlyPrint;
        boolean isLastTrade = Params.sL3Params.isLastTrade;
        if (oriVoucherNo != null && oriVoucherNo.length() > 0) {
            PayDetail payDetail = mPayDetailModel.getSuccessPayDetailByVoucherNo(oriVoucherNo);
            startPrint(payDetail, isOnlyPrint);
        } else if (transId != null && transId.length() > 0) {
            PayDetail payDetail = mPayDetailModel.getPayDetailByCustomOrderNo(transId);
            startPrint(payDetail, isOnlyPrint);
        } else if (isLastTrade) {
            PayDetail payDetail = mPayDetailModel.getLastSuccessTrade();
            startPrint(payDetail, isOnlyPrint);
        } else {
            startPrint(null, isOnlyPrint);
        }
    }

    private void startPrint(PayDetail payDetail, boolean isPrint) {
        if (payDetail == null) {
            TransactionPrintActivity.startAction(mL3Route);
        } else {
            if (isPrint) {
                printSalesSlip(1, payDetail);
                L3BroadcastHelper.sendResultBroadcast(mL3Route, true, payDetail);
            } else {
                FillInTheCertificateActivity.startAction(mL3Route, payDetail.voucherNo, true);
            }
        }
    }

    private void printSalesSlip(final int pageNum, final PayDetail payDetail) {
        BasePrintController controller = new PrintController();
        try {
            int state = DataPrinterKernel.INSTANCE().updatePrinterState();
            if (state == 1) {
                controller.print(payDetail, null, pageNum, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 13.查询商户信息
     */
    public void handleQueryMerchantInfo() {
        L3BroadcastHelper.sendMerchantInfoBroadcast(mL3Route);
    }

    /**
     * 15.签退
     */
    public void handleSignOut() {
        int count = PayDetailModel.getInstance().getTransactionList().size();
        if (count > 0) {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_TRADE_NO_SETTLEMENT);
            mL3Route.finish();
        } else {
            SignOutCtrl signOutCtrl = new SignOutCtrl(mL3Route);
            signOutCtrl.signOut();
        }
    }

    /**
     * 16.联机交易记录查询
     */
    public void handleQueryByOnline() {
        // 12 扫码交易末笔查询
        if (Params.sL3Params.transType == 12) {
            Params.sL3Params.isLastTrade = true;
            Params.sL3Params.lastTradeType = 0;
        }
        QueryByOnline query = new QueryByOnline(mL3Route);
        query.queryTradeByOnline();
    }

    /**
     * 18.本地交易记录查询
     * 如果传入凭证号，则按凭证号查询
     * 如果传入第三方订单号，则按第三方订单号查询
     * 如果传入为空，则为查询全部
     * 查询顺序：凭证号，第三方订单号
     */
    public void handleQueryByLocal() {
        String transId = Params.sL3Params.transId;
        String oriVoucherNo = Params.sL3Params.oriVoucherNo;
        String oriReferenceNo = Params.sL3Params.oriReferenceNo;
        PayDetail payDetail;
        if (oriVoucherNo != null && oriVoucherNo.length() > 0) {
            payDetail = mPayDetailModel.getPayDetailById(oriVoucherNo);
            L3BroadcastHelper.sendResultBroadcast(mL3Route, true, payDetail);
        } else if (transId != null && transId.length() > 0) {
            payDetail = mPayDetailModel.getPayDetailByCustomOrderNo(transId);
            L3BroadcastHelper.sendResultBroadcast(mL3Route, true, payDetail);
        } else if (oriReferenceNo != null && oriReferenceNo.length() > 0) {
            payDetail = mPayDetailModel.getPayDetailByTransRefNo(oriReferenceNo);
            L3BroadcastHelper.sendResultBroadcast(mL3Route, true, payDetail);
        } else {
            List<PayDetail> list = mPayDetailModel.getAllTrades();
            L3BroadcastHelper.sendAllTradeListBroadcast(mL3Route, list);
        }
    }

    /**
     * 20.设置签购单抬头
     */
    public void handleRiseString() {
        L3Params l3Params = Params.sL3Params;
        String riseString = l3Params.riseString;
        if (riseString != null && riseString.length() > 0) {
            SalesSlipPrintSettingsOperation settingsOperation = SalesSlipPrintSettingsOperation.getInstance();
            settingsOperation.saveRiseString(riseString);
            settingsOperation.saveRise(0);
            L3BroadcastHelper.sendSuccessBroadcast(mL3Route);
        } else {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_RISE_STRING_FAIL);
        }
    }

    /**
     * 22.订单支付结果查询
     */
    public void handleOrderQuery() {
        L3Params params = Params.sL3Params;
        params.isCustomOrderNo = true;
        String transId = params.transId;
        String date = params.oriTransDate;
        if (transId == null || transId.length() == 0) {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_INVALID_ORDER_ID);
            mL3Route.finish();
        } else if (date == null || date.length() == 0) {
            L3BroadcastHelper.sendFailedBroadcast(mL3Route, L3ErrorCode.ERROR_INVALID_DATE);
            mL3Route.finish();
        } else {
            PayOrderResultQueryController ctrl = new PayOrderResultQueryController(mL3Route);
            ctrl.queryQRCodeResult();
        }
    }

    private void openActivity(Class clazz) {
        Intent intent = new Intent(mL3Route, clazz);
        mL3Route.startActivity(intent);
    }

}
